package com.neusoft.elm.infrastructure.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.elm.infrastructure.exception.GlobalExceptionHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

public class DispatcherServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        //中文编码处理
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        //获取客户端请求路径(/business/list)
        String path = request.getServletPath();
        System.out.println("收到请求路径: " + path);
        
        // 验证路径格式
        if (path == null || path.isEmpty() || !path.contains("/")) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("{\"code\":400,\"message\":\"无效的请求路径\"}");
            return;
        }

        // 移除开头的斜杠
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        
        // 分割路径获取类名和方法名
        String[] pathParts = path.split("/");
        if (pathParts.length < 2) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("{\"code\":400,\"message\":\"请求路径格式错误，应为：/business/list\"}");
            return;
        }

        String className = pathParts[0];
        String methodName = pathParts[1];
        System.out.println("解析出的类名: " + className + ", 方法名: " + methodName);
        
        // 将路径转换为控制器类名（例如：business -> BusinessController）
        className = className.substring(0, 1).toUpperCase() + className.substring(1) + "Controller";
        System.out.println("转换后的完整类名: " + className);

        PrintWriter out = null;

        try {
            //通过Controller类全名获取此类的所有信息
            String fullClassName = "com.neusoft.elm.controller." + className;
            System.out.println("尝试加载类: " + fullClassName);
            Class<?> clazz = Class.forName(fullClassName);
            //创建Controller类的对象
            Object controller = clazz.newInstance();
            //获取Controller类对象中的方法
            Method method = clazz.getMethod(methodName,new Class[]{HttpServletRequest.class});
            System.out.println("找到方法: " + method.getName());
            //调用上面获取的方法
            Object result = method.invoke(controller,new Object[]{request});
            System.out.println("方法执行结果: " + result);

            //获取向客户端响应的输出流
            out = response.getWriter();
            ObjectMapper om = new ObjectMapper();
            //向客户端响应json数据
            String jsonResult = om.writeValueAsString(result);
            System.out.println("返回的JSON数据: " + jsonResult);
            out.print(jsonResult);

        } catch(ClassNotFoundException e) {
            System.err.println("找不到控制器类: " + e.getMessage());
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("{\"code\":404,\"message\":\"找不到对应的控制器\"}");
        } catch(NoSuchMethodException e) {
            System.err.println("找不到方法: " + e.getMessage());
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("{\"code\":404,\"message\":\"找不到对应的方法\"}");
        } catch(Exception e) {
            System.err.println("发生异常: " + e.getMessage());
            e.printStackTrace();
            GlobalExceptionHandler.handleException(e, request, response);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doPost(request,response);
    }
} 